package com.edushare.common.util;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.wicket.RequestCycle;
import org.apache.wicket.protocol.http.RequestUtils;

import com.edushare.common.constants.ConfigPropertyName;
import com.edushare.common.constants.URLConstants;
import com.edushare.common.global.SystemGlobals;
import com.edushare.common.vo.Assignments;
import com.edushare.common.vo.Courses;
import com.edushare.common.vo.Departments;
import com.edushare.common.vo.FilesUploaded;
import com.edushare.common.vo.SystemBackup;
import com.edushare.common.vo.Universities;
import com.edushare.common.vo.Users;

public class URLUtils {
	
	private static Log log = LogFactory.getLog(URLUtils.class);
	
	public static String escapeSplChars(String input) {
		// TODO Auto-generated method stub
		String pattern = "[^A-Za-z0-9_\\-]";
		input = StringUtil.replaceLongSpacesToSingle(input);
		input = input.replace(" ", "-");
		input = StringUtil.replace(input, pattern, "");
		return input;
	}
	
	public static String escapeSplCharsFromFileName(String input) {
		// TODO Auto-generated method stub
		String pattern = "[^A-Za-z0-9_\\-\\.]";
		input = StringUtil.replaceLongSpacesToSingle(input);
		input = input.replace(" ", "-");
		input = StringUtil.replace(input, pattern, "");
		return input;
	}

	public static String[] splitIntoLabelAndURL(String urlLabel) {
		if(!StringUtil.isValid(urlLabel))
			return new String[]{"", ""};
		if(!urlLabel.contains(">>"))
			return new String[]{urlLabel, urlLabel};
		String url = urlLabel.substring(0, urlLabel.indexOf(">>"));
		String label = urlLabel.substring(urlLabel.indexOf(">>")+2);
		return new String[]{url, label};
	}
	
	/**
	 * Absolute home page URLs for universities, courses, departments and users.
	 * <b>NOTE: THE SERVLET PATHS ARE *HARDCODED* HERE. USED FOR MAIL SENDING PURPOSE ONLY. USE in.muton.edushare.url.* INSTEAD</b>
	 * 
	 * @return absolute URL to EduShare entity home page.
	 */
	public static final String getHomePageURL(Object object){
		
		if(object instanceof Universities){
			return RequestUtils.toAbsolutePath(URLConstants.UNIVERSITY_PROFILE_PATH+"/"+((Universities)object).getUniqueName());
		}
		else if(object instanceof Departments)
		{
			return RequestUtils.toAbsolutePath(
					URLConstants.DEPARTMENT_PROFILE_PATH + "/" +
					URLUtils.escapeSplChars(((Departments)object).getDeptName()) + "/" +
					((Departments)object).getDepartmentId());
		}
		else if(object instanceof Courses)
		{
			return RequestUtils.toAbsolutePath(
					URLConstants.COURSE_PROFILE_PATH+"/"+
					URLUtils.escapeSplChars(((Courses)object).getCourseName())+"/"+
					((Courses)object).getCourseId());
		}else if(object instanceof Users){
			return RequestUtils.toAbsolutePath(
					URLConstants.USER_PROFILE_PATH + "/" +
					((Users)object).getUserName());
		}else if(object instanceof Assignments){
			return RequestUtils.toAbsolutePath(
					URLConstants.ASSIGNMENT_PATH + "/" +((Assignments)object).getAssignmentId());
		}
		return null;
	}

	public static String generateTeacherInviteURL(String key) {
		String base =  RequestUtils.toAbsolutePath(URLConstants.VERIFY_INVITE_PATH);
		return base+"?key="+key;
	}
	
	public static String generatePasswordResetURL(String key){
		String base = RequestUtils.toAbsolutePath(URLConstants.PASSWORD_RESET);
		return base+"?key="+key;
	}

	public static String getImageUrlFromRelativePath(String profileImageRelativePath) {
		String base = SystemGlobals.getInstance().getConfigProperty(ConfigPropertyName.UPLOAD_FILE_SERVER);
		if(StringUtil.isValid(profileImageRelativePath))
			return base + profileImageRelativePath;
		return null;
	}
	
	/** In case file upload server and image server are different*/
	public static String getUrlFromRelativePath(String fileRelativePath) {
		String base = SystemGlobals.getInstance().getConfigProperty(ConfigPropertyName.UPLOAD_FILE_SERVER);
		if(StringUtil.isValid(fileRelativePath))
			return base + fileRelativePath;
		return null;
	}

	public static String getUserSeoUrl(Users user) {
		String uname = escapeSplChars(user.getUserName());
		return RequestUtils.toAbsolutePath(uname);
	}

	public static String createFileDownloadURL(FilesUploaded filesUploaded) {
		String relativePath = 
			URLConstants.FILE_DOWNLOAD_PATH+"/"+
			filesUploaded.getFileUploadedId()+"/"+
			escapeSplCharsFromFileName(filesUploaded.getFileOrigName());
		
		String absUrl = RequestCycle.get().getRequest().getRelativePathPrefixToContextRoot()+ relativePath;
		
		return absUrl;
	}

	public static String getVersionFromRelativePath(String uri) {
		String version = "";
		if(!StringUtil.isValid(uri))
			return "";
		String[] fragments = uri.split("/");
		if(fragments.length>0 && fragments[0].contains(":")){
				version = fragments[0].split(":")[1];
			
		}
		return version;
	}
	
	public static int getFileIdFromRelativePath(String uri) {
		int fileId = 0;
		if(!StringUtil.isValid(uri))
			return 0;
		String[] fragments = uri.split("/");
		if(fragments.length>0){
			String fileIdStr = fragments[0];
			if(fileIdStr.contains(":"))
				fileIdStr = fileIdStr.split(":")[0];
			
			try{
				fileId = Integer.parseInt(fileIdStr);
			}catch(NumberFormatException nfe){
				log.error("Number format exception while parsing file id. Relative URL is "+uri);
			}
		}
		return fileId;
	}

	public static String getFileVersionUrlFromCompleteUrl(String url, String fileSuffix) {
		
		if(!StringUtil.isValid(url))
			return url;
		
		String[] fragments = url.split("/");
		int i=0;
		boolean mountFound = false;
		String fileIdFrag = null;
		String newUrl = "";
		
		//if it's default image treat differently
		boolean isDefault = false;
		for(String part: fragments){
			if(part.equals(URLConstants.DEFAULT_IMG_DIR)){
				isDefault = true;
				break;
			}
		}
		
		if(isDefault)
			return getFileVersionUrlFromDefaultUrl(url, fileSuffix);
		
		//the the file mount block
		for(String part: fragments){
			if(StringUtil.isValid(part) && part.equalsIgnoreCase(URLConstants.FILE_DOWNLOAD_PATH)){
				mountFound = true;
				break;
			}else{
				++i;
			}
		}
		
		//next to file-mount (index = i+1) block we have fileId:version
		if(mountFound && fragments.length>i+2){
			fileIdFrag = fragments[i+1];
			//if it's versioned URL strip off the version
			if(fileIdFrag.contains(":")){
				fileIdFrag = fileIdFrag.split(":")[0];
			}
			
			fileIdFrag = fileIdFrag + ":" + fileSuffix;
		}
		
		//if FileIdFrag makes any sense, replace in the array
		if(StringUtil.isValid(fileIdFrag)){
			fragments[i+1] = fileIdFrag;
		}
		
		//re-bind the fragments
		for(String str: fragments){
			newUrl = newUrl +str + "/";
		}
		
		if(StringUtil.isValid(newUrl) && newUrl.endsWith("/")){
			newUrl = newUrl.substring(0, newUrl.length()-1);
		}
		
		if(!StringUtil.isValid(newUrl))
			newUrl = url;
		
		return newUrl;
	}

	public static String getFileVersionUrlFromDefaultUrl(String url, String fileSuffix) {
		if(!StringUtil.isValid(url))
			return url;
		
		return url.substring(0, url.lastIndexOf(".")) + "_" + fileSuffix + url.substring(url.lastIndexOf("."));
	}

	public static String getBackupFileDownloadURL(SystemBackup systemBackup, String fileName) {
		String relativePath = 
			URLConstants.BACKUP_DOWNLOAD_PATH+"/"+
			systemBackup.getSystemBackupId()+"/"+
			escapeSplCharsFromFileName(fileName);
		
		String absUrl = RequestCycle.get().getRequest().getRelativePathPrefixToContextRoot()+ relativePath;
		
		return absUrl;
	}

}
